//
//  StatusPictureView.swift
//  我的微博
//
//  Created by ZhangChao on 15/9/9.
//  Copyright © 2015年 ZhangChao. All rights reserved.
//

import UIKit
import SDWebImage

private let statusPictureCellID = "statusPictureCellID"

class StatusPictureView: UICollectionView {

    var statusViewModel : StatusViewModel?{
        didSet{
            
            sizeToFit()
            // 不刷新数据 后果很严重
            reloadData()
        }
    }
    
    // sizeToFit方法内部会调用这个方法
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return caculatorViewSize()
    }
    
    // 计算View的大小
    private func caculatorViewSize () -> CGSize{
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: statusPictureItemWidth, height: statusPictureItemWidth)
        
        //根据图片的数量来计算视图的宽高
        let count = statusViewModel?.thumbnailUrl?.count ?? 0
        
        // 没有图片
        if count == 0 {
            
            return CGSizeZero
        }
        // 有一张图片
        if count == 1 {
            
            var size = CGSize(width: 150, height: 150)
            
            // 获取图像的全路径是否存在
            let key = statusViewModel?.thumbnailUrl![0].absoluteString
            
            // 如果有缓存的图片,记录图片大小
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key){
                
                size = image.size
            }
            // 单独处理过宽或者过窄的图片
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > 300 ? 300 : size.width
            
            // 设置单个视图的大小
            layout.itemSize = size
            
            // 返回整个View的大小
            return size
        }
        
        // 有四张图片
        if count == 4 {
            
            let w = 2 * statusPictureItemWidth + statusPictureItemMargin
            
            return CGSize(width: w, height: w)
            
        }
        
        // 其他 2,3,5,6,7,8,9
        let row = CGFloat((count - 1) / Int(statusPictureMaxCount) + 1)
        let h = row * statusPictureItemWidth + (row - 1) * statusPictureItemMargin
        let w = statusPictureMaxWidth
        
        return CGSize(width: w, height: h)
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        // 这里的flowLaout记得要初始化
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        backgroundColor = UIColor.lightGrayColor()
        
        // 设置每张小图片之间的间距
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumInteritemSpacing = statusPictureItemMargin
        layout.minimumLineSpacing = statusPictureItemMargin
        
        // 设置数据源方法
        dataSource = self
        // 注册cell
        registerClass(StatuesPictureViewCell.self, forCellWithReuseIdentifier: statusPictureCellID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
// 数据源方法
extension StatusPictureView : UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return statusViewModel?.thumbnailUrl?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureCellID, forIndexPath: indexPath) as! StatuesPictureViewCell
        
        cell.imageURL = statusViewModel?.thumbnailUrl![indexPath.item]
        
        return cell
    }
}

// 配图视图的cell
private class StatuesPictureViewCell: UICollectionViewCell{
    
    var imageURL : NSURL?{
        didSet{
            // 设置配图视图
         iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    // 在构造方法中赋值
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 添加图像
        addSubview(iconView)
        // 布局
        iconView.ff_Fill(self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var iconView : UIImageView = {
        
        let imageView = UIImageView()
        
        // 设置图片的填充模式
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        
        return imageView
        
    }()
    
}